﻿using CoreShop.App.Properties;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.PrintService;
using CoreShop.Services;
using FastMember;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml.Linq;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;
using static Sunny.UI.UIAvatar;
using static System.Net.Mime.MediaTypeNames;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace CoreShop.App
{
    public partial class frmSelectFoods : UIForm
    {
        public int mBillType = 0;//单据类型

        private int mTypePageIndex = 1;//分类页码
        private int mTypePageSize = 10;//分类页码大小
        private int mTypeRowCount = 0;//分类数据条数        

        private int mFoodPageIndex = 1;//商品页码
        private int mFoodPageSize = 10;//商品页码大小
        private int mFoodRowCount = 0;//商品数据条数      
        private long mFoodTypeId = 0;//商品分类ID，分组用

        public List<corecmsfoodordering> orderingDetail = new List<corecmsfoodordering>();
        public corecmsfoodordering orderingSelected = null;
        private UIMenuItem uiMenuItemSelected = null;
        public corecmsuser member = null;
        private bool isFocusInput = false;
        static System.Timers.Timer timer_focus = null;
        public corecmsfoodordering orderingParent;

        public frmSelectFoods(int _BillType,string sName)
        {
            mBillType = _BillType;
            InitializeComponent();
            this.lblBillName.Text = sName;
            this.lblBillCaption.Text = EnumHelper.GetDescByValue<GlobalEnumVars.BillType>(_BillType);                
            if (timer_focus == null)
            {
                timer_focus = new System.Timers.Timer();
                timer_focus.Interval = 200;
                timer_focus.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
                timer_focus.Enabled = true;
            }
        }        

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //timer_focus.Enabled = false;
                if (!isFocusInput)
                {
                    this.txtInput.Invoke(new Action(() =>
                    {
                        this.txtInput.Focus();
                    }));
                }
            }
            catch { }
        }

        #region 控件机关

        /// <summary>
        /// 根据指定容器和控件名字，获得控件
        /// </summary>
        /// <param name="obj">容器</param>
        /// <param name="strControlName">控件名字</param>
        /// <returns>控件</returns>
        private object GetControlInstance(object obj, string strControlName)
        {
            IEnumerator Controls = null;//所有控件
            Control c = null;//当前控件
            Object cResult = null;//查找结果
            if (obj.GetType() == this.GetType())//窗体
            {
                Controls = this.Controls.GetEnumerator();
            }
            else//控件
            {
                Controls = ((Control)obj).Controls.GetEnumerator();
            }
            while (Controls.MoveNext())//遍历操作
            {
                c = (Control)Controls.Current;//当前控件
                if (c.HasChildren)//当前控件是个容器
                {
                    cResult = GetControlInstance(c, strControlName);//递归查找
                    if (cResult == null)//当前容器中没有，跳出，继续查找
                        continue;
                    else//找到控件，返回
                        return cResult;
                }
                else if (c.Name == strControlName)//不是容器，同时找到控件，返回
                {
                    return c;
                }
            }
            return null;//控件不存在
        }

        private string GetMenuItemName(long orderingId)
        {
            return "uiMenuItem_" + orderingId.ToString();
        }

        private string GetFoodTypeButtonName(long foodTypeId)
        {
            return "btnFoodType_" + foodTypeId.ToString();
        }

        #endregion      

        private void FOrdering_Load(object sender, EventArgs e)
        {
            CreateFoodType();
            BindFoodType();
            CreateFoodList();
            SetBillTotal();
            switch (mBillType)
            {
                case (int)GlobalEnumVars.BillType.TempStorage:
                    btnSetOK.Text = "存入";
                    break;
                case (int)GlobalEnumVars.BillType.PackDetail:
                    btnSetOK.Text = "选择";
                    break;
                default:

                    break;
            }
        }

        private void Form1_Shown(object sender, System.EventArgs e)
        {
            //this.WindowState = FormWindowState.Maximized;           
            BindFoodList(0);            
        }

        #region 商品分类按钮及数据

        private void CreateFoodTypeBtn(int index, ref int mLeft, int mTop)
        {
            UIButton btn = new UIButton();
            btn.Name = "btnFoodType_" + index.ToString();
            btn.Parent = pnl_center_top_foodtype1;
            btn.Tag = index;
            btn.Left = mLeft;
            btn.Top = mTop;
            btn.Text = "商品分类" + index.ToString();
            btn.BackColor = btnFoodType_1.BackColor;
            btn.Cursor = btnFoodType_1.Cursor;
            btn.FillColor = btnFoodType_1.FillColor;
            btn.FillColor2 = btnFoodType_1.FillColor2;
            btn.FillHoverColor = btnFoodType_1.FillHoverColor;
            btn.FillPressColor = btnFoodType_1.FillPressColor;
            btn.FillSelectedColor = btnFoodType_1.FillSelectedColor;
            btn.Font = btnFoodType_1.Font;
            btn.ForeHoverColor = btnFoodType_1.ForeHoverColor;
            btn.ForePressColor = btnFoodType_1.ForePressColor;
            btn.ForeSelectedColor = btnFoodType_1.ForeSelectedColor;
            btn.MinimumSize = btnFoodType_1.MinimumSize;
            btn.Radius = btnFoodType_1.Radius;
            btn.RectColor = btnFoodType_1.RectColor;
            btn.RectHoverColor = btnFoodType_1.RectHoverColor;
            btn.RectPressColor = btnFoodType_1.RectPressColor;
            btn.RectSelectedColor = btnFoodType_1.RectSelectedColor;
            btn.Size = btnFoodType_1.Size;
            btn.Style = btnFoodType_1.Style;
            btn.StyleCustomMode = btnFoodType_1.StyleCustomMode;
            btn.TipsFont = btnFoodType_1.TipsFont;
            btn.ForeColor = btnFoodType_1.ForeColor;
            btn.TipsColor = btnFoodType_1.TipsColor;
            btn.TipsForeColor = btnFoodType_1.TipsForeColor;
            btn.ShowTips = btnFoodType_1.ShowTips;
            btn.Click += this.btnFoodType_1_Click;
            mLeft = btn.Left + btn.Width + 2;
        }

        private void CreateFoodType()
        {
            decimal btnCounts = pnl_center_top_foodtype.Width / btnFoodType_1.Width;
            int mRowSize = CommFunc.ConvertToInt32(Math.Floor(btnCounts)) - 3;
            int mLeft = btnFoodType_1.Left + btnFoodType_1.Width + 2;
            int mTop = btnFoodType_1.Top;
            mTypePageSize = mRowSize * 2 + 1;
            for (int i = 2; i <= mTypePageSize; i++)
            {
                if (i == mRowSize + 1)
                {
                    mLeft = btnAllType.Left;
                    mTop = btnFoodType_1.Top + btnFoodType_1.Height + 15;
                }
                CreateFoodTypeBtn(i, ref mLeft, mTop);
            }
        }

        private void CleareFoodTypeBtn()
        {
            for (int i = 1; i <= mTypePageSize; i++)
            {
                string btnName0 = "btnFoodType_" + i.ToString();
                UIButton btnType = (UIButton)GetControlInstance(this, btnName0);
                if (btnType != null) btnType.Visible = false;
            }
        }

        private void SetFoodTypePageState()
        {
            if (mTypeRowCount <= mTypePageSize)
            {
                btnFoodTypePre.Enabled = false;
                btnFoodTypeNext.Enabled = false;
            }
            else if (mTypePageIndex == 1)
            {
                btnFoodTypePre.Enabled = false;
                btnFoodTypeNext.Enabled = true;
            }
            else if (mTypePageIndex * mTypePageSize > mTypeRowCount)
            {
                btnFoodTypePre.Enabled = true;
                btnFoodTypeNext.Enabled = false;
            }
            else
            {
                btnFoodTypePre.Enabled = true;
                btnFoodTypeNext.Enabled = true;
            }
        }

        private void SetFoodTypeTips(long mTypeId)
        {
            for (int i = 1; i <= mTypePageSize; i++)
            {
                string btnName0 = "btnFoodType_" + i.ToString();
                UIButton btnType = (UIButton)GetControlInstance(this, btnName0);
                if (CommFunc.ConvertToBtInt(btnType.Tag) == mTypeId)
                {


                }
            }

        }

        private void BindFoodType()
        {
            CleareFoodTypeBtn();
            int btnIndex = 1;
            if (mTypePageIndex < 1) mTypePageIndex = 1;
            var typeList = new corecmsfoodcategoryServices().QueryPageAsync(ref mTypeRowCount, mTypePageIndex, mTypePageSize, "", AppConstVars.sysStore);            
            foreach (var item in typeList)
            {
                string btnName = GetFoodTypeButtonName(btnIndex);
                try
                {
                    UIButton btnType = (UIButton)GetControlInstance(this, btnName);
                    btnType.Tag = item.id.ToString();
                    btnType.Text = item.name;
                    btnType.Visible = true;
                    if ((btnIndex == 3) || (btnIndex == 7))
                    {
                        //btnType.TipsText = btnIndex.ToString();
                    }
                }
                catch { }
                btnIndex += 1;
            }
            SetFoodTypePageState();
        }

        #endregion

        #region 商品列表相关
        /// <summary>
        /// 商品按钮名称
        /// </summary>
        /// <param name="deskId"></param>
        /// <returns></returns>
        private string GetFoodItemName(int index)
        {
            return "uiFoodItem_" + index.ToString();
        }

        /// <summary>
        /// 建空的单个商品按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreateFoodListBtn(int index)
        {
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "";
            //dish.Money = food.posPrice.ToString()+"/"+ food.foodSpecName;
            dish.Money = "";
            dish.UnitName = "";
            //if (food.isHeft.ObjToBool())
            //{
            //    dish.LabelExist = "剩 10,000 份";
            //    dish.DiscountString = "3个优惠";
            //}
            var item = new UIDishItem(dish);
            item.Name = GetFoodItemName(index);
            item.Visible = false;
            if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
            //item.TipsText = RandomEx.RandomNumber(1);
            item.Margin = new System.Windows.Forms.Padding(3);
            item.Tag = "";
            item.Click += Item_Click;
            fly_foodlist.Add(item);
        }

        /// <summary>
        /// 建空的商品按钮
        /// </summary>
        private void CreateFoodList()
        {
            fly_foodlist.Clear();
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "默认";
            dish.Money = "0.00";
            dish.UnitName = "";
            var item = new UIDishItem(dish);

            if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
            item.Margin = new System.Windows.Forms.Padding(3);
            decimal itemCols = (fly_foodlist.Width - 10) / (item.Width + 3);
            decimal itemRows = (fly_foodlist.Height - 10) / (item.Height + 3);

            mFoodPageSize = CommFunc.ConvertToInt32(Math.Floor(itemCols)) * CommFunc.ConvertToInt32(Math.Floor(itemRows));
            for (int i = 1; i <= mFoodPageSize; i++)
            {
                CreateFoodListBtn(i);
            }
        }

        /// <summary>
        /// 暂不显示所有商品商品
        /// </summary>
        private void HiddenFoodList(int starIndex)
        {
            for (int i = starIndex; i <= mFoodPageSize; i++)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(i));
                var item = (UIDishItem)mControl;
                if (item != null) item.Visible = false;
            }
        }

        private Expressionable<corecmsfood, corecmsfoodspec> GetExpressionable(long mFoodTypeId)
        {
            var where = Expressionable.Create<corecmsfood, corecmsfoodspec>();
            where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0 && s.onLine == true);
            string sName = txtInput.Text;
            if (!string.IsNullOrEmpty(sName))
                where = where.And((f, s) => f.name.Contains(sName) || f.number.Contains(sName) || s.code.Contains(sName)
                || f.byName.Contains(sName) || f.helpCode.Contains(sName) || f.pinYin.Contains(sName));

            if (mFoodTypeId > 0)
            {
                var typeIds = new corecmsfoodcategoryServices().AsQueryable()
                .Where(p => p.parentId == mFoodTypeId).Select(p => p.id).ToList();

                if (typeIds.Count > 0)
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId || typeIds.Contains(f.foodTypeId));
                else
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId);
            }

            return where;
        }

        private void BindFoodList(long mFoodTypeId,int keyValue = 0)
        {
            if (mFoodPageIndex < 1) mFoodPageIndex = 1;
            var foodSoldouts = new corecmsfoodsoldoutServices().QueryFoodSoldouts();

            var foodList = new corecmsfoodServices().QueryPageAsync(ref mFoodRowCount, mFoodPageIndex, mFoodPageSize, GetExpressionable(mFoodTypeId));
            int index = 1;
            var orderingUnit = new OrderingUtil();
            fly_foodlist.Visible = false;
            AppConstVars.isDownLoadFile = false;
            this.fly_foodlist.SuspendLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
            foreach (var food in foodList)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(index));
                var item = (UIDishItem)mControl;
                if (item != null)
                {
                    item.Tag = food.id.ToString();
                    item.Visible = true;
                    item.TextName = food.name;
                    var dish = item.Info;
                    dish.Name = food.name;
                    dish.Money = food.posPrice.ToString();
                    dish.LabelExist = orderingUnit.GetFoodSoldout(foodSoldouts, food);
                    //dish.DiscountString = orderingUnit.GetFoodDiscount(foodSoldouts, food);                    
                    //item.TipsText = RandomEx.RandomNumber(1);
                    SetDishItemImage(item, food);//加载商品图片                    
                    item.Refresh();
                }
                index++;
            }
            HiddenFoodList(index);
            this.fly_foodlist.ResumeLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
            fly_foodlist.Visible = true;
            fly_foodlist.Refresh();
            SetFoodListPageState();
            downLoadStart();
        }

        private void SetDishItemImage(UIDishItem item,corecmsfood food)
        {
            try
            {
                if (!AppConstVars.systemsetup.showFoodImg) return;
                if (string.IsNullOrEmpty(food.image))
                {
                    item.Image = Resources.NoImage;
                    return;
                }
                string imagePath = System.Windows.Forms.Application.StartupPath + "\\foodimg\\";
                string filename = imagePath + System.IO.Path.GetFileName(food.image);
                if (File.Exists(filename))
                {
                    item.Image = System.Drawing.Image.FromFile(filename);
                    return;
                }
                AppConstVars.isDownLoadFile = true;
                AppConstVars.downLoadFile.AddDown(food.image, imagePath, 0, filename);
            }
            catch { }
        }

        private void downLoadStart()
        {
            if (AppConstVars.isDownLoadFile) AppConstVars.downLoadFile.StartDown();
        }

        private void SetFoodListPageState()
        {
            if (mFoodRowCount <= mFoodPageSize)
            {
                btnFoodListPre.Enabled = false;
                btnFoodListNext.Enabled = false;
            }
            else if (mFoodPageIndex == 1)
            {
                btnFoodListPre.Enabled = false;
                btnFoodListNext.Enabled = true;
            }
            else if (mFoodPageIndex * mFoodPageSize > mFoodRowCount)
            {
                btnFoodListPre.Enabled = true;
                btnFoodListNext.Enabled = false;
            }
            else
            {
                btnFoodListPre.Enabled = true;
                btnFoodListNext.Enabled = true;
            }
        }


        private void SetFoodTypeUnSelect()
        {
            for (int i = 1; i <= mTypePageSize; i++)
            {
                string btnName0 = "btnFoodType_" + i.ToString();
                UIButton btnType = (UIButton)GetControlInstance(this, btnName0);
                if (btnType != null) btnType.Selected = false;
            }
        }

        #endregion

        #region 表格（点单）绑定相关

        private MenuItemInfo BindOrderingItemInfo(corecmsfoodordering item)
        {
            MenuItemInfo info = new MenuItemInfo();
            info.Count = item.quantity.ToString("0.##");
            if (item.foodPackId > 0)
            {
                info.Name = ">" + item.name;
                //info.ForeColor = Color.Gray;
                info.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(69)))), ((int)(((byte)(120)))), ((int)(((byte)(103)))));
                if (item.allAmount == 0) info.Money = "";
                else info.Money = item.allAmount.ToString("0.##");
            }
            else
            {
                info.Name = item.name;
                info.Money = item.allAmount.ToString("0.##");
            }
            return info;
        }

        private void BindOrdering()
        {
            try
            {
                layOrdering.Visible = false;
                var orderingfoodList = new corecmsfoodServices().QueryByIdsAsync(orderingDetail.Select(p=>p.foodId).Distinct().ToList());
                layOrdering.Clear();
                uiMenuItemSelected = null;
                List<corecmsfoodordering> orderingDiscounts = new List<corecmsfoodordering>();
                foreach (var item in orderingDetail)
                {
                    item.foodImage = orderingfoodList.Find(p => p.id.Equals(item.foodId)).image;
                    if (item.dataType == (int)GlobalEnumVars.OrderingDataType.Present || item.dataType == (int)GlobalEnumVars.OrderingDataType.Discount)
                    {
                        orderingDiscounts.Add(item);
                    }
                    else
                    {                        
                        this.layOrdering.SuspendLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
                        MenuItemInfo info = BindOrderingItemInfo(item);
                        UIMenuItem menu = new UIMenuItem(info);
                        menu.Name = GetMenuItemName(item.id);
                        menu.Margin = new System.Windows.Forms.Padding(0);
                        menu.Tag = item.id;
                        menu.Click += MenuItem_Click;
                        layOrdering.Add(menu);
                        layOrdering.Panel.ScrollControlIntoView(menu);
                        this.layOrdering.ResumeLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
                        if (orderingSelected == null) orderingSelected = item;
                        if (orderingSelected.id == item.id)
                        {
                            uiMenuItemSelected = menu;
                            pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
                        }
                    }
                }

                if ((orderingDiscounts != null) && (orderingDiscounts.Count > 0))
                {
                    var sp = new UIMenuItemSeparator();
                    layOrdering.Add(sp);
                    foreach (var item in orderingDiscounts)
                    {
                        MenuItemInfo info = BindOrderingItemInfo(item);
                        UIMenuItem menu = new UIMenuItem(info);
                        menu.Name = GetMenuItemName(item.id);
                        menu.Margin = new System.Windows.Forms.Padding(0);
                        menu.Tag = item.id;
                        menu.Click += MenuItem_Click;
                        layOrdering.Add(menu);
                        if (orderingSelected == null) orderingSelected = item;
                        if (orderingSelected.id == item.id)
                        {
                            uiMenuItemSelected = menu;
                            pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
                        }
                    }
                }

                if (uiMenuItemSelected != null) uiMenuItemSelected.Selected = true;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错-BindOrdering:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
            finally
            {
                layOrdering.Visible = true;
            }
            int ScrollWidth = this.layOrdering.VerticalScroll.Maximum;
            this.layOrdering.AutoScrollPosition = new Point(0, ScrollWidth);
            SetBillTotal();
        }
                
        #endregion 

        #region 做法与加料

        /// <summary>
        /// 判断是否有选择行,modifyFlag = true时要修改，
        /// </summary>
        /// <returns></returns>
        private bool IsOrderSelected(bool modifyFlag = false)
        {
            if (orderingSelected == null)
            {
                ShowInfoTip("没有选择行,无法操作。");
                return false;
            }
            if ((modifyFlag) && (orderingSelected.itemStatus == (int)OrderingItemStatus.PreSettled))
            {
                ShowInfoTip("该商品已下单,无法操作");
                return false;
            }
            if ((modifyFlag) && (orderingSelected.itemType == (int)GlobalEnumVars.FoodType.PackChild))
            {
                ShowInfoTip("套餐内商品,无法操作");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 刷新绑定单行数据，不必清除再新增控件
        /// </summary>
        /// <param name="orderId"></param>
        private void BindOrderingRow(corecmsfoodordering item)
        {
            try
            {
                if (item == null)
                {
                    layOrdering.Clear();
                    return;
                }
                var mControl = layOrdering.Get(GetMenuItemName(item.id));
                var menu = (UIMenuItem)mControl;
                MenuItemInfo info = menu.Info;
                info.Name = item.name;
                info.Count = item.quantity.ToString("0.##");
                info.Money = item.allAmount.ToString("0.##");
                if (item.foodPackId > 0)
                {
                    info.Name = ">" + item.name;
                    info.ForeColor = Color.Gray;
                    info.Money = "";
                }
                else
                {
                    info.Name = item.name;
                    info.Money = item.allAmount.ToString("0.##");
                }
                layOrdering.Refresh();
                SetBillTotal();
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错-BindOrdering:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }


        #endregion

        private void AddDataRow(long foodId, Decimal hQty)
        {
            corecmsfoodorderingmaster orderingMaster = null;
            string msgStr = "所选择的商品不存在或没有选择商品规格。";
            var ordering = ProcessUtil.CreateByFoodId(Program.frmMainWin, orderingMaster, foodId, 0,1,null, null, ref msgStr);
            if (ordering == null)
            {
                UIMessageBox.Show(msgStr, "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            if (ordering.quantity == 0) return;

            this.txtInput.Clear();
            this.txtInput.Focus();

            if ((ordering.itemType == (int)GlobalEnumVars.FoodType.PackFood) || (ordering.itemType == (int)GlobalEnumVars.FoodType.TempPack))
            {
                UIMessageBox.Show("无法添加套菜类型的商品。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK); ;
                return;
            }
            ordering.id = YitIdHelper.NextId();
            ordering.realPrice = CommFunc.GetRowAmount(ordering.realPrice, AppConstVars.systemsetup.rowAmountDecimal);
            ordering.realAmount = CommFunc.GetRowAmount(ordering.realPrice * ordering.quantity, AppConstVars.systemsetup.rowAmountDecimal);

            if (mBillType == (int)GlobalEnumVars.BillType.PackChild)
            {
                ordering.price = 0;
                ordering.amount = 0;
                ordering.realPrice = 0;
                ordering.allAmount = 0;
            }

            ordering.orderId = 0;
            orderingDetail.Add(ordering);
            orderingSelected = ordering;
            BindOrdering();
        }

        /// <summary>
        /// 保存数据，
        /// </summary>
        /// <param name="type">type=0全部保存，type=1，保存选择行</param>
        /// <param name="editFieldType">1修改数据，2修改单价，3修改金额，4修改折扣</param>
        private void SaveOrdering(int saveType, int editFieldType)
        {
            bool bl = false;

            //修改数量，计算金额
            if ((editFieldType == 1) || (editFieldType == 2))
            {
                orderingSelected.amount = orderingSelected.quantity * orderingSelected.price;
                orderingSelected.realAmount = orderingSelected.quantity * orderingSelected.realPrice;
                orderingSelected.allAmount = orderingSelected.realAmount + orderingSelected.taskAmount + orderingSelected.feedAmount;
            }
            var row = orderingDetail.Find(p => p.id == orderingSelected.id);
            if (row != null)
            {
                row.quantity = orderingSelected.quantity;
                row.amount = orderingSelected.amount;
                row.allAmount = orderingSelected.allAmount;
                BindOrderingRow(row);
            }
        }

        public void SetBillTotal()
        {
            lblAllAmount.Text = "0.00";
            lblSumQuantity.Text = string.Format("共{0}项", 0);
            lblQuantity.Text = "数量:0";
            if (orderingDetail != null)
            {
                lblAllAmount.Text = orderingDetail.Sum(p=>p.allAmount).ToString("#0.0#");
                lblSumQuantity.Text = string.Format("共{0}项", orderingDetail.Count);
                lblQuantity.Text = string.Format("数量:{0}", orderingDetail.Sum(p => p.quantity)); 
            }
        }

        private void Item_Click(object sender, System.EventArgs e)
        {
            UIDishItem item = (UIDishItem)sender;
            AddDataRow(CommFunc.ConvertToBigInt(item.Tag), 1);
        }          

        private void btnAllType_Click(object sender, EventArgs e)
        {
            BindFoodType();
            SetFoodTypeUnSelect();
            mTypePageIndex = 1;
            mFoodTypeId = 0;
            BindFoodList(0);
        }

        private void btnFoodType_1_Click(object sender, EventArgs e)
        {
            var btn = (UIButton)sender;
            btn.Selected = true;
            mFoodPageIndex = 1;
            mFoodTypeId = CommFunc.ConvertToInt64(btn.Tag);
            BindFoodList(mFoodTypeId);
        }

        private void btnFoodTypeNext_Click(object sender, EventArgs e)
        {
            mTypePageIndex += 1;
            BindFoodType();
        }

        private void btnFoodTypePre_Click(object sender, EventArgs e)
        {
            mTypePageIndex -= 1;
            BindFoodType();
        }

        private void MenuItem_Click(object sender, System.EventArgs e)
        {
            uiMenuItemSelected = (UIMenuItem)sender;
            long id = CommFunc.ConvertToInt64(uiMenuItemSelected.Tag);
            orderingSelected = orderingDetail.Find(p=>p.id == id);
            if (orderingSelected == null)
            {
                UIMessageBox.Show("获取数据失败", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
            orderingSelected.quantity = pnl_left_number.Text.ObjToInt(0);
        }

        private void btnAddQty_Click(object sender, EventArgs e)
        {
            if (!IsOrderSelected(true)) return;
            if (pnl_left_number.Text.ObjToDecimal() > 1)
            {
                pnl_left_number.Text = (pnl_left_number.Text.ObjToDecimal() - 1).ToString();
                orderingSelected.quantity = pnl_left_number.Text.ObjToDecimal(0);
                SaveOrdering(1, 1);
            }                          
        }

        private void btnCutQty_Click(object sender, EventArgs e)
        {
            if (!IsOrderSelected(true)) return;
            pnl_left_number.Text = (pnl_left_number.Text.ObjToDecimal() + 1).ToString();            
            orderingSelected.quantity = pnl_left_number.Text.ObjToDecimal(0);
            SaveOrdering(1, 1);
        }      

        private void btnRemoveRow_Click(object sender, EventArgs e)
        {
            if (!IsOrderSelected(true)) return;            
            //if (!ShowAskDialog("确认要删除当前选择的商品吗？")) return;
            long id = orderingSelected.id;
            var delItem = orderingDetail.Find(p => p.id == id);
            if (delItem != null)
            {
                orderingDetail.Remove(delItem);
                orderingSelected = null;
                BindOrdering();
            }            
        }
                
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ShowAskDialog("确认要取消本单数据吗？")) return;

                orderingDetail = new List<corecmsfoodordering>();
                orderingSelected = null;
                BindOrdering();
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
            }
        }
                
        private void FOrdering_Activated(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void txtInput_OkButtonClick(object sender, string value)
        {
            mFoodPageIndex = 1;
            BindFoodList(0);
        }

        private void btnFoodListPre_Click(object sender, EventArgs e)
        {
            mFoodPageIndex -= 1;
            BindFoodList(mFoodTypeId);
        }

        private void btnFoodListNext_Click(object sender, EventArgs e)
        {
            mFoodPageIndex += 1;
            BindFoodList(mFoodTypeId);
        }


        private void pnl_left_number_Click(object sender, EventArgs e)
        {
            #region 判断数据项
            if (orderingSelected == null)
            {
                ShowInfoTip("没有选择行,无法操作。");
                return;
            }
            if (orderingSelected.itemType == (int)GlobalEnumVars.FoodType.PackChild)
            {
                ShowInfoTip("套餐内商品,无法操作");
                return;
            }
            var foodspec = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
            if (foodspec == null)
            {
                ShowInfoTip("该商品规格不存在,无法操作");
                return;
            }
            #endregion
            frmFoodSpecWeigh foodSpecWeigh = new frmFoodSpecWeigh(orderingSelected, foodspec);
            foodSpecWeigh.Owner = Program.frmMainWin;
            if (foodSpecWeigh.ShowDialog() == DialogResult.OK)
            {
                decimal dQuantity = CommFunc.ConvertToDecimal(foodSpecWeigh.mScaleQty);
                orderingSelected.specName = foodSpecWeigh.txtSpecName.Text;
                orderingSelected.quantity = CommFunc.ConvertToDecimal(dQuantity);
                pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
                SaveOrdering(1, 1);
                ShowInfoTip("修改成功。");
            }
        }

        private DateTime dLastTime = DateTime.Now;  //定义一个成员函数用于保存每次的时间点,用户判断是扫描还是手工录入
        private void txtInput_TextChanged(object sender, EventArgs e)
        {
            DateTime tempDt = DateTime.Now;          //保存按键按下时刻的时间点
            TimeSpan ts = tempDt.Subtract(dLastTime);     //获取时间间隔
            if (ts.Milliseconds > 100)  //判断时间间隔，如果时间间隔大于50毫秒，则将判断为手工输入
            {
                mFoodPageIndex = 1;
                BindFoodList(0);
            }
            dLastTime = tempDt;
        }

        private void FOrdering_ReceiveParams(object sender, UIPageParamsArgs e)
        {
            this.txtInput.Focus();
        }

        private void txtInput_Leave(object sender, EventArgs e)
        {
            isFocusInput = false;
        }

        private void FOrdering_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!isFocusInput)
            {
                this.txtInput.Focus();
            }            
        }

        private void txtInput_Enter(object sender, EventArgs e)
        {
            isFocusInput = true;
        }

        private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)13) return;
            long foodId = 0;
            int foodCount = 0;
            foreach (var ctrl in this.GetControls<UIDishItem>(true))
            {
                if (ctrl.Visible)
                {
                    foodCount += 1;
                    foodId = CommFunc.ConvertToInt64(ctrl.Tag);
                }
            }
            if ((foodCount == 1) && (foodId >0)) AddDataRow(foodId, 1);
        }

        private void sbtHome_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void GetMemberInfo()
        {
            btnGetMember.Text = "会员登录";
            lblMemberPhone.Text = "";
            lblMemberAmount.Text = "";
            if (member != null)
            {
                btnGetMember.Text = "会员电话";
                lblMemberPhone.Text = member.mobile;
                lblMemberAmount.Text = "余额：" + member.balance.ObjToString("0.0##");
            }
        }

        private void btnGetMember_Click(object sender, EventArgs e)
        {
            var frm = new FrmUserGetInfo(member);
            frm.Owner = this;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                member = frm.member;
                GetMemberInfo();
            }
            frm.Dispose();
        }

        /// <summary>
        /// 临时套餐保存
        /// </summary>
        private bool SavePackFood()
        {
            orderingParent.sourceId = (long)YitIdHelper.NextId();
            var foodorderingList = new List<corecmsfoodordering> { orderingParent };
            int rowId = orderingParent.rowId;
            foreach (var item in orderingDetail)
            {
                rowId++;
                item.orderId = orderingParent.orderId;
                item.sourceId = orderingParent.sourceId;
                item.billerId = AppConstVars.sysUser.id;
                item.price = 0;
                item.amount = 0;
                item.realPrice = 0;
                item.allAmount = 0;
                item.foodPackQuantity = item.quantity;
                item.itemType = (int)GlobalEnumVars.FoodType.PackChild;
                item.foodPackId = orderingParent.foodId;
                item.rowId = rowId;
                foodorderingList.Add(item);
            }

            var bl = new corecmsfoodorderingServices().InsertRange(foodorderingList);
            if (!bl)
            {
                UIMessageBox.Show("保存失败。", "系统出错-SaveOrderingFeed:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 寄存保存
        /// </summary>
        private bool SaveDepositary()
        {
            if (member == null) btnGetMember_Click(null, null);
            if (member == null)
            {
                UIMessageBox.Show("没有读取会员，不能保存。", "系统提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return false;
            }
            var orderId = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId()); 
            var data = new List<corecmsdepositarydetail>();
            foreach (var item in orderingDetail)
            {
                var depositary = new corecmsdepositarydetail();
                depositary.orderId = orderId;
                depositary.userId = member.id;
                depositary.sysUserId = AppConstVars.sysUser.id;
                depositary.storeId = AppConstVars.sysUser.storeId;
                depositary.foodId = item.foodId;
                depositary.foodSpecId = item.foodSpecId;
                depositary.quantity = item.quantity;
                depositary.orderDate = DateTime.Now;
                depositary.sourceId = 0;
                data.Add(depositary);
            }
            string msg = "";
            //var bl = new PosRemoteServices(AppConstVars.sUrl).DoCreateDepositary(data, AppConstVars.sysUser.ccessToken, ref msg);
            //if (!bl)
            //{
            //    UIMessageBox.Show(msg, "保存失败", UIStyle.Black, UIMessageBoxButtons.OK);
            //    return false;
            //}
            return true;
        }

        private void btnSetOK_Click(object sender, EventArgs e)
        {
            switch (mBillType)
            {
                case (int)GlobalEnumVars.BillType.PackChild:
                    if (!SavePackFood()) return;
                    break;
                case (int)GlobalEnumVars.BillType.TempStorage:
                    if (!SaveDepositary()) return;
                    break;
            }           
            
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}